import { addMonth, format } from "@ui/utils/date";
import { getZksj, getZkxmList, getZkpDxList } from "@api";
import { yqList } from "@utils";
import { loadComponent } from "@ui/utils/vue";
const tabTitle = [
  { title: '图形', id: 'tx' },
  { title: '有效数据', id: 'yxsj' },
  { title: '所有数据', id: 'sysj' },
  { title: '质控评价', id: 'zkpj' }
]
function getZkDxBz(param: any) {
  return getZkpDxList(param).then(({ data: { list } }) => {
    const zksj = {}
    list.forEach((it) => {
      if (zksj[it.zkpid]) {
        zksj[it.zkpid].push(it)
      } else {
        zksj[it.zkpid] = [it]
      }
    })
    return Object.values(zksj)
  })
}
function getZkDlBz(param: any) {
  return getZkpDxList(param).then(({ data: { list } }) => {
    const zksj = {}
    list.forEach((it) => {
      if (zksj[it.zkpid]) {
        zksj[it.zkpid].push(it)
      } else {
        zksj[it.zkpid] = [it]
      }
    })
    return Object.values(zksj)
  })
}
function getZkBz(gz: string, xmid: string, yqid: string) {
  switch (gz) {
    case '定性质控':
      return getZkDxBz({ xmid, yqid })
      break
    default:
      return getZkDlBz({ xmid, yqid })
  }
}
export function use() {
  const formData = ref<LisZkZktFormData>({ yqid: '', ph: '6', kssj: format(addMonth(-3)), jssj: format(new Date()), dt: '', xsfljd: '', xssyph: '', dy: '', dw: '9', sp1: '1', sp2: '1', sp3: '1' }),
    tableLoading = ref(false),
    tableList = ref<LisZkxmItem[]>([]),
    zksj = ref<LisZksjItem[]>([]),
    zkParam = ref({ yqmc: '', kssj: '', jssj: '', zbmc: '', zkgzdldm: '' }),
    zkbz = ref([])
  var clickRow: LisZkxmItem
  watch(() => ({ kssj: formData.value.kssj, jssj: formData.value.jssj }), () => tableClick(clickRow))
  watch(() => formData.value.yqid, (yqid) => {
    if (yqid) {
      tableLoading.value = true
      getZkxmList({ yqid }).then(({ data: { list } }) => {
        tableList.value = list
      }).finally(() => {
        tableLoading.value = false
        tableClick(tableList.value[0] as LisZkxmItem)
      })
    } else {
      tableList.value = []
      tableClick()
    }
  })
  function tableClick(row: LisZkxmItem = {} as LisZkxmItem) {
    const { yqid, zbid, zkgzdldm } = row, { kssj, jssj } = formData.value
    clickRow = row
    if (zbid) {
      getZksj({ yqid, zbid, kssj: kssj + ' 00:00:00', jssj: jssj + ' 23:59:59' }).then(({ data: { list } }) => {
        zkParam.value = {
          yqmc: (yqList.value.filter(it => it.id == yqid)[0] || {}).yqmc || '',
          kssj, jssj, zbmc: row.zbmc || '', zkgzdldm: row.zkgzdldm || ''
        }
        zksj.value = list
      })
      getZkBz(zkgzdldm, zbid, yqid).then(res => {
        zkbz.value = res
      })
    } else {
      zksj.value = []
    }
  }
  return {
    formData, tableLoading, tableList,
    tabTitle, yqList, tableClick, zksj, zkParam,
    loadComponent: loadComponent(import.meta.glob('./module/**/*.vue')),
    zkbz
  }
}